package controller;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import po.User;
import service.UserService;
import utils.SessionString;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    //登录检测
    @RequestMapping(value = "/userLogin.action",method = RequestMethod.POST)
    public String login( String username,  String password, Model model, HttpSession httpSession){
        //model是用于数据传递
        User user = userService.findUserByNameAndPassword(username,password);
        if(user != null){
            httpSession.setAttribute(SessionString.USER_SESSION,user);
            return "forward:/BookAll";//返回到用户购书的界面
        }else{
            httpSession.setAttribute(SessionString.MSG,"账号或密码有误，请重新输入！");
            return "userLogin";
        }
    }
    //直接进行登录验证
    @RequestMapping(value = "/userLogin.action",method = RequestMethod.GET)
    public String toLogin(){
        return "userLogin";
    }
    //用户注册
    @RequestMapping(value = "/userRegister.action")
    public String register(User user,HttpSession httpSession){
        //添加好数据后,跳转到数据
        int  row = userService.addNewUser(user);
        if(row > 0){
            httpSession.setAttribute(SessionString.MSG,"你已经注册成功可以进行登录!");
            return "userLogin";//返回登录的页面
        }else{
            return "ok";//返回注册错误的页面
        }
    }
    //用户退出
    @RequestMapping(value = "/logoutUser.action")
    public String logout(HttpSession httpSession){
        httpSession.invalidate();
        return "userLogin";
    }
}
